package com.ruoyi.reservoir.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.reservoir.domain.Image;
import com.ruoyi.reservoir.domain.InterpretationTask;
import com.ruoyi.reservoir.domain.TaskPlot;
import com.ruoyi.reservoir.domain.dto.TaskSubDto;
import com.ruoyi.reservoir.domain.vo.TaskVo;
import com.ruoyi.reservoir.mapper.InterpretationTaskMapper;
import com.ruoyi.reservoir.service.IImageService;
import com.ruoyi.reservoir.service.IInterpretationTaskService;
import com.ruoyi.reservoir.service.ITaskPlotService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static com.ruoyi.common.constant.ReservoirConstants.*;

@Slf4j
@Service
@DS("slave")
@RequiredArgsConstructor
public class InterpretationTaskServiceImpl extends ServiceImpl<InterpretationTaskMapper, InterpretationTask> implements IInterpretationTaskService {

    private final IImageService iImageService;

    private final ITaskPlotService taskPlotService;

    /**
     * 解译管理-分页查询解译任务列表
     * @param pageNo
     * @param pageSize
     * @param plotType
     * @param field
     * @param sort
     * @param userId
     * @return
     */
    @Override
    public IPage<TaskVo> getInterpretationTaskList(Integer pageNo,
                                                   Integer pageSize,
                                                   String plotType,
                                                   String field,
                                                   String sort,
                                                   Long userId) {

        //是否需要排序
        Boolean sortFlag = !StringUtils.isEmpty(field);
        sort = sortFlag && StringUtils.isEmpty(sort) ? "DESC" : sort;

        QueryWrapper<InterpretationTask> queryWrapper = new QueryWrapper<>();
        queryWrapper
            .lambda()
            .like(InterpretationTask::getPlotType, plotType)
            //筛除未解译完成的任务
            .ne(InterpretationTask::getTaskStatus, "待解译")
            .ne(InterpretationTask::getTaskStatus, "解译中")
            //查询系统解译和当前用户手动创建的任务
            .and(qw -> qw
                .isNull(InterpretationTask::getUserId)
                .or()
                .eq(InterpretationTask::getUserId, userId)
            )
            //默认排序
            .orderByAsc(!sortFlag, InterpretationTask::getSortNum)
            .orderByDesc(!sortFlag, InterpretationTask::getCreateTime);

        /*
            自定义排序
         */
        queryWrapper.lambda()
            //解译时间
            .orderByDesc(sortFlag && "createTime".equals(field) && "DESC".equals(sort), InterpretationTask::getCreateTime)
            .orderByAsc(sortFlag && "createTime".equals(field) && "ASC".equals(sort), InterpretationTask::getCreateTime)
            //影像采集时间
            .orderByDesc(sortFlag && "captureTime".equals(field) && "DESC".equals(sort), InterpretationTask::getImageCaptureTime)
            .orderByAsc(sortFlag && "captureTime".equals(field) && "ASC".equals(sort), InterpretationTask::getImageCaptureTime)
            //图斑总数量
            .orderByDesc(sortFlag && "plotNum".equals(field) && "DESC".equals(sort), InterpretationTask::getPlotNumber)
            .orderByAsc(sortFlag && "plotNum".equals(field) && "ASC".equals(sort), InterpretationTask::getPlotNumber)
            //图斑总面积
            .orderByDesc(sortFlag && "plotArea".equals(field) && "DESC".equals(sort), InterpretationTask::getPlotArea)
            .orderByAsc(sortFlag && "plotArea".equals(field) && "ASC".equals(sort), InterpretationTask::getPlotArea);

        Page<InterpretationTask> page = new Page<>(pageNo, pageSize);
        Page<InterpretationTask> iPage = baseMapper.selectPage(page, queryWrapper);

        //封装当期影像信息
        Set<String> imageIdSet = iPage.getRecords()
            .stream()
            .map(InterpretationTask::getImageId)
            .collect(Collectors.toSet());
        Map<String, Image> imageMap = iImageService.getImageMap(imageIdSet);

        IPage<TaskVo> convert = iPage.convert(task -> {

            TaskVo bean = BeanUtil.toBean(task, TaskVo.class);

            //封装影像信息
            String imageId = task.getImageId();
            Image image = imageMap.getOrDefault(imageId, new Image());
            bean.setImageName(image.getImageName());
            bean.setImageResolution(image.getImageResolution());

            return bean;
        });

        return convert;
    }

    /**
     * 解译管理-批量任务提交
     * @param taskIdSet
     * @return
     */
    @Override
    @Transactional
    public R<?> taskSubmission(Set<String> taskIdSet) {

        if (taskIdSet.isEmpty()){
            return R.fail("提交任务列表不能为空！");
        }

        //待提交的任务
        List<InterpretationTask> list = lambdaQuery()
            .in(InterpretationTask::getId, taskIdSet)
            .eq(InterpretationTask::getTaskStatus, TASK_STATUS_NOTSUB)
            .list();

        //校验是否有相同地物，相同期数的任务已被提交
        List<TaskSubDto> taskSubDtos = taskSubedVerification(list);
        if (!taskSubDtos.isEmpty()){
            return R.fail(MESSAGE_SUBED, taskSubDtos);
        }

        /*
            修改状态
         */

        //1.修改图斑状态 -> 未审核
        LambdaUpdateWrapper<TaskPlot> plotUpdateWrapper = new LambdaUpdateWrapper<>();
        plotUpdateWrapper
            .in(TaskPlot::getTaskId, taskIdSet)
            .set(TaskPlot::getPlotStatus, TASK_STATUS_NOTEXAMINE);
        boolean plotUpdate = taskPlotService.update(plotUpdateWrapper);

        //2.修改任务状态 -> 未审核
        LambdaUpdateWrapper<InterpretationTask> taskUpdateWrapper  = new LambdaUpdateWrapper<>();
        taskUpdateWrapper
            .in(InterpretationTask::getId, taskIdSet)
            .set(InterpretationTask::getTaskStatus, TASK_STATUS_NOTEXAMINE);
        boolean taskUpdate = this.update(taskUpdateWrapper);

        boolean flag = plotUpdate && taskUpdate;
        if (!flag){
            throw new RuntimeException("任务提交失败");
        }

        return R.ok("任务提交成功");
    }

    /**
     * 解译任务是否重复提交校验
     * @param list
     * @return
     */
    private List<TaskSubDto> taskSubedVerification(List<InterpretationTask> list) {
        /*
            校验是否有相同地物，相同期数的任务已被提交
         */

        //1.任务状态为（未审核或审核通过）的任务为已提交任务
        LambdaQueryWrapper<InterpretationTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
            .and(qw -> qw
                .eq(InterpretationTask::getTaskStatus, TASK_STATUS_NOTEXAMINE)
                .or()
                .eq(InterpretationTask::getTaskStatus, TASK_STATUS_APPROVED)
            );
        //2.校验提交的任务中，是否有相同地物，相同期数的任务已被提交
        queryWrapper
            .and(qw -> {
                    for (InterpretationTask task : list) {
                        qw.or(orQw -> orQw
                            .eq(InterpretationTask::getPlotType, task.getPlotType())
                            .and(andQw -> andQw
                                .eq(InterpretationTask::getImageCaptureTime, task.getImageCaptureTime())
                            ));
                    }
                }
            );

        //查询校验结果
        List<InterpretationTask> taskList = baseMapper.selectList(queryWrapper);

        /*
            封装校验结果
            1.列表为空则通过校验、2.列表不为空则存在重复任务
         */
        List<TaskSubDto> taskSubDtos = taskList
            .stream()
            .map(task -> {
                TaskSubDto bean = BeanUtil.toBean(task, TaskSubDto.class);
                bean.setReason(RESON_SUBED);
                return bean;
            })
            .collect(Collectors.toList());

        return taskSubDtos;
    }
}
